package com.tarena.lbs.user.service.Impl;

import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.BusinessApi;
import com.tarena.lbs.business.api.pojo.BusinessDto;
import com.tarena.lbs.common.enums.PassportResultEnum;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.param.AdminParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.query.AdminQuery;
import com.tarena.lbs.user.pojo.vo.AdminVO;
import com.tarena.lbs.user.service.AdminService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private UserRepository  userRepository;
    
    @DubboReference
    private BusinessApi businessApi;

    @Override
    public void save(AdminParam param) throws BusinessException {
        // 获取当前登录用户
        UserPrinciple currentUser = AuthenticationContextUtils.get();
        if (currentUser == null) {
            throw new BusinessException(PassportResultEnum.USER_NONE_EXIST);
        }
        
        // 判断当前用户是否为管理员
        if (currentUser.getRole().getType() != Roles.ADMIN.getType()) {
            throw new BusinessException(PassportResultEnum.ADMIN_NONE_EXIST);
        }

        // 参数校验'账号类型 平台管理员=0 商家账号=1',
        if (param.getAccountType() == null) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }

        if (param.getBusinessId() == null && (param.getAccountType() == Roles.SHOP.getType())) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }
        if (!StringUtils.hasText(param.getAccountPhone())) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }
        if (!StringUtils.hasText(param.getAccountPassword())) {
            throw new BusinessException(PassportResultEnum.EMPTY_PASSWORD);
        }
        if (!StringUtils.hasText(param.getNickname())) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }
        if (!StringUtils.hasText(param.getEmail())) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }
        if (param.getAccountStatus() == null) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }

        // 检查手机号是否已注册
        AdminPO existAdmin = adminRepository.findByPhone(param.getAccountPhone());
        if (existAdmin != null) {
            throw new BusinessException(PassportResultEnum.USER_EXIST);
        }

        // 如果是商家账号，需要验证商家是否存在
        if (param.getAccountType() == Roles.SHOP.getType()) {
            try {
                BusinessDto business = businessApi.getBusinessById(param.getBusinessId());
                if (business == null) {
                    throw new BusinessException(PassportResultEnum.USER_NONE_EXIST);
                }
                if (business.getBusinessStatus() != 1) {
                    throw new BusinessException(PassportResultEnum.SYSTEM_ERROR);
                }
            } catch (Exception e) {
                throw new BusinessException(PassportResultEnum.SYSTEM_ERROR);
            }
        }

        // 创建管理员对象
        AdminPO admin = new AdminPO();
        BeanUtils.copyProperties(param, admin);
        
        // 设置额外字段
        admin.setCreateTime(new Date());
        
        // 保存管理员
        adminRepository.save(admin);
    }

    @Override
    public AdminVO getAdminDetail() throws BusinessException {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2","请先登录"));
        Integer id = userPrinciple.getId();
        AdminPO adminPO = adminRepository.getAdminById(id);
        AdminVO adminVO = null;
        if (adminPO != null){
            adminVO = new AdminVO();
            BeanUtils.copyProperties(adminPO,adminVO);
        }
        return adminVO;
    }

    @Override
    public PageResult<AdminVO> AdminPageList(AdminQuery query) {
        PageInfo<AdminPO> pageInfo = adminRepository.adminPageList(query);
        PageResult<AdminVO> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        List<AdminVO> vos = null;
        if ((!CollectionUtils.isEmpty(pageInfo.getList()))){
            vos = pageInfo.getList().stream().map(po -> {
                AdminVO vo = new AdminVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        pageResult.setObjects(vos);

        return pageResult;
    }

} 